package com.loozb.thread3;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 重入锁
 * @author 龙召碧
 * @create 2018-01-30 17:17
 **/
public class ReenterLock implements Runnable {
    public static ReentrantLock lock = new ReentrantLock();

    public static int i = 0;

    @Override
    public void run() {
        for (int j = 0; j < 10000000;j ++) {
            try {
                //尝试获取锁。如果当前有别的线程获取了锁，则睡眠。可中断锁
                lock.lockInterruptibly();
                try {
                    i ++;
                } finally {
                    lock.unlock();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                if(lock.isHeldByCurrentThread()) {
                    lock.unlock();
                }
            }
        }
    }

    /**
     * 如果使用new AccountingVol()，则上锁需要用静态static
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        ReenterLock t = new ReenterLock();
        Thread t1 = new Thread(t);
        Thread t2 = new Thread(t);
        t1.start();t2.start();
        t1.join();t2.join();
        System.out.println(i);
    }
}
